<template>
  <div class="right-board">
    <el-tabs v-model="currentTab" class="center-tabs">
      <el-tab-pane label="主题" name="field" />
    </el-tabs>
    <div class="field-box">
      
      <el-scrollbar class="right-scrollbar">
        <!-- 组件属性 -->
        <el-form v-show="currentTab==='field'" size="small" label-width="90px">

          <el-form-item v-if="configData.isSelfAdaption!==undefined" label="是否自适应">
            <el-switch v-model="configData.isSelfAdaption" active-text="是" inactive-text="否"/>
          </el-form-item>

          <el-form-item v-if="configData.adaptionType!==undefined && configData.isSelfAdaption == true" label="自适应类型">
              <el-radio-group v-model="configData.adaptionType" class="adaption_radio">
                <el-radio label="0">全自适应</el-radio>
                <el-radio label="1">宽度自适应</el-radio>
                <el-radio label="2">高度自适应</el-radio>
              </el-radio-group>
            </el-form-item>

          <el-form-item v-if="configData.panelWidth!==undefined" label="大屏宽度">
            <el-input-number controls-position="right" v-model="configData.panelWidth"></el-input-number>
          </el-form-item>

          <el-form-item v-if="configData.panelHeight!==undefined" label="大屏高度">
            <el-input-number controls-position="right" v-model="configData.panelHeight"></el-input-number>
          </el-form-item>

          <el-form-item v-if="configData.bgColor!==undefined" label="背景颜色">
            <el-color-picker v-model="configData.bgColor" show-alpha />
          </el-form-item>

          <el-form-item v-if="configData.bgImage!==undefined" label="背景图片">
            <img style="width: 200px; height: 150px; cursor: pointer;" :src="basePath + configData.bgImage" @click="openGallery" ></el-image>
          </el-form-item>

          <el-form-item v-if="configData.themeColor!==undefined" label="主题颜色">
            <!--
            <el-select v-model="configData.themeColor" placeholder="请选择">
              <el-option
                v-for="item in themeColorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            -->
            <div class="theme-plan-group" style="cursor: pointer;" @click="openTheme">
              <div class="theme-plan-color"
                v-for="c in (configData.themeColor.color)"
                :style="{'background-color': c}">
              </div>
            </div>
            <a href="https://echarts.apache.org/zh/theme-builder.html" target="_blank" style="color: #5470c6">主题配置</a>
          </el-form-item>

        </el-form>
        
      </el-scrollbar>
    </div>

    <!-- 图库对话框 -->
    <el-dialog title="图库" :visible.sync="open" width="1000px" hight="600px" append-to-body>
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="所属模板">
        <el-input
            v-model="queryParams.viewTemplate"
            placeholder="请输入所属模板"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="uploadOpenModel">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            
        </el-form-item>
      </el-form>

      <div style="overflow:auto; height:500px;">
        <ul
            class="background-images-ul"
            v-infinite-scroll="load"
            infinite-scroll-disabled="disabled">
           
            <li v-for="item in uploadList" @click="selectImg(item.imagePath)" style="overflow:hidden">
              <img :src="basePath + item.imagePath" class="border_img">
              <label :title="item.name">{{ item.name }}</label>
              <span title="删除" class="drawing-item-delete" @click.stop="deleteBackground(item.uploadId)"><i class="el-icon-delete"></i></span>
            </li>
        </ul>
        <p v-if="loading" style="text-align: center; margin-top: 100px;">加载中...</p>
        <p v-if="noMore" style="text-align: center; margin-top: 100px;">没有更多了</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="reset">重置</el-button>
        <el-button @click="cancel">取 消</el-button>        
      </div>
    </el-dialog>

    <!-- 添加或修改数据大屏文件上传映射对话框 -->
    <el-dialog title="上传图片" :visible.sync="uploadOpen" width="500px" append-to-body>
      <el-form ref="uploadForm" :model="uploadForm" :rules="rules"  label-width="80px">

        <el-form-item label="是否公开" prop="isOpen">
            <el-radio-group v-model="uploadForm.isOpen">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="是否模板素材" prop="isTemplate" v-if="adminRole">
            <el-radio-group v-model="uploadForm.isTemplate">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
            </el-radio-group>
        </el-form-item>         
        <el-form-item label="所属模板" prop="viewTemplate">
          <el-input v-model="uploadForm.viewTemplate" style="width: 360px" placeholder="请输入所属模板" />
        </el-form-item>

        <el-form-item label="上传">
            <el-upload
            class="upload-demo"
            drag
            action
            :http-request="httpRequest"
            :show-file-list="false" :before-upload="beforeUpload"
            multiple>
            <i class="el-icon-upload"></i>
            </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">提交</el-button>
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 自定义主题库对话框 -->
    <el-dialog title="主题库" :visible.sync="themeOpen" width="1200px" hight="600px" append-to-body>

      <el-form :model="themeQueryParams" ref="themeQueryParams" :inline="true" label-width="68px">
        <el-form-item label="主题名称">
        <el-input
            v-model="themeQueryParams.themeName"
            placeholder="主题名称"
            clearable
            size="small"
            style="width: 240px"
        />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleThemeQuery">搜索</el-button>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="uploadOpenTheme">上传<i class="el-icon-upload el-icon--right"></i></el-button>
        </el-form-item>
      </el-form>

      <div style="overflow-y:auto;overflow-x:hidden; height:500px;">
        <ul
            class="background-images-ul"
            v-infinite-scroll="themeLoad"
            infinite-scroll-disabled="themeDisabled">
            <div class="row">
              <div class="col-xs-6" style="white-space: nowrap;overflow:hidden" v-for="item in themeList" @click="selectTheme(JSON.parse(item.themeOption))">
                <span title="删除" class="drawing-item-delete" @click.stop="deleteTheme(item.themeId)"><i class="el-icon-delete"></i></span>
                <div class="theme-plan-color"
                  v-for="c in (JSON.parse(item.themeOption).color)"
                  :title="item.themeName"
                  :style="{'background-color': c}">
                </div>
              
              </div>
            </div>
        </ul>
     
        <p v-if="themeLoading" style="text-align: center; margin-top: 100px;">加载中...</p>
        <p v-if="themeNoMore" style="text-align: center; margin-top: 100px;">没有更多了</p>
       

      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTheme">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改数据大屏文件上传映射对话框 -->
    <el-dialog title="上传主题" :visible.sync="themeUploadOpen" width="500px" append-to-body>
      <el-form ref="themeForm" :model="themeForm"  label-width="80px">

        <el-form-item label="是否公开">
            <el-radio-group v-model="themeForm.isOpen">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
            </el-radio-group>
        </el-form-item>       
        <el-form-item label="主题名称">
          <el-input v-model="themeForm.themeName" style="width: 360px" placeholder="请输入主题名称" />
        </el-form-item>

        <el-form-item label="主题配置json">
          <el-input v-model="themeForm.themeOption" type="textarea" rows="20" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitThemeUpload">提交</el-button>
        <el-button @click="cancelThemeUpload">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { listUpload, fileUpload, delUpload } from "@/api/tool/datav/fileUpload";
import { listTheme, addTheme, delTheme } from "@/api/tool/datav/theme";
import VueEvent from '@/views/tool/datav/VueEvent'

export default {

  props: ["costomData"],
  data() {
    return {
      basePath: process.env.VUE_APP_BASE_API,
      currentTab: 'field',
      configData: this.costomData,
      open: false,
      themeColorOptions: [{label:'macarons', value: 'macarons'}, {label:'azul', value: 'azul'}, {label:'bee-inspired', value: 'bee-inspired'}, {label:'blue', value: 'blue'}, {label:'caravan', value: 'caravan'}, {label:'cool', value: 'cool'}, {label:'fresh-cut', value: 'fresh-cut'}, {label:'fruit', value: 'fruit'}, {label:'helianthus', value: 'helianthus'}, {label:'sakura', value: 'sakura'}],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: '0',
        sort: undefined,
        viewTemplate: undefined,
      },
      rules: {
        isOpen: [
          { required: true, message: "是否公开不能为空", trigger: "blur" }
        ],
      },
      uploadList: [],
      total: -1,
      loading: false,
      uploadOpen: false,
      uploadForm: {
        isOpen:"0",
        isTemplate: "0",
      },
      fileList: [],
      themeOpen: false,
      themeQueryParams: {
        pageNum: 1,
        pageSize: 10,
        themeName: undefined
      },
      themeList: [],
      themeTotal: -1,
      themeLoading: false,
      themeUploadOpen: false,
      themeForm: {},
      adminRole: false,//管理员权限
    }
  },
  //页面加载完执行
  mounted() {
    
  },
  created() {
    let roles = this.$store.getters.roles;
    let result = roles.find(ele => ele === 'admin')//判断是否包含admin权限
    if (result) {
      this.adminRole = true;
    };
  },
  computed: {
    noMore () {
      if(this.total != -1) {
        return this.total == this.uploadList.length
      } else {
        return false;
      }
    },
    disabled () {
      return this.loading || this.noMore
    },
    themeNoMore () {
      if(this.themeTotal != -1) {
        return this.themeTotal == this.themeList.length
      } else {
        return false;
      }
    },
    themeDisabled () {
      return this.themeLoading || this.themeNoMore
    }
  },
  watch: {
    configData: {
      deep: true,
      handler(newVal) {
        // console.log("1=>", newVal);
        //this.$emit("costom-change", newVal);
      }
    },
    costomData: {
      deep: true,
      handler(newVal) {
        // console.log("barConfig=>costomData.watch")
        this.configData = newVal;
        //this.staticDataValue = JSON.stringify(newVal.chartOption.staticDataValue);
      }
    },
    'configData.panelWidth':{
      handler(newValue,oldValue){
        // console.log('Watch: OldpanelWidth',oldValue,' NewpanelWidth',newValue)
        VueEvent.$emit("canvasResize",this.configData.panelWidth);
      }
    },
    'configData.panelHeight':{
      handler(newValue,oldValue){
        // console.log('Watch: OldpanelHeight',oldValue,' NewpanelHeight',newValue)
        VueEvent.$emit("canvasResize",this.configData.panelHeight);
      }
    }
  },
  methods: {
    openGallery() {
      this.total = -1;
      this.uploadList = [];
      this.queryParams.pageNum = 1;
      this.open = true;
      this.load();
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    //重置
    reset(){
      this.$set(this.configData, 'bgImage', '');
      this.open = false;
    },
    handleQuery() {
      this.total = -1;
      this.uploadList = [];
      this.queryParams.pageNum = 1;
      this.open = true;
      this.load();
    },
    load () {
      this.loading = true;
      listUpload(this.queryParams).then(response => {
        this.uploadList = this.uploadList.concat(response.rows);
        this.total = response.total;
        this.queryParams.pageNum++;
        this.loading = false;
      });
    },
    selectImg(item) {
      this.$set(this.configData, 'bgImage', item);
      //this.configData.chartOption.border = item;
      this.open = false;
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      }
    },
    //取消上传
    cancelUpload() {
        this.uploadOpen = false;
    },
    uploadOpenModel() {
        this.uploadOpen = true;
    },
    //自定义上传,重写文件上传方法,覆盖原有的上传方法，将上传的文件依次添加到fileList数组中
    httpRequest(option) {
        this.fileList.push(option);
        this.msgSuccess("成功上传至浏览器缓存");
    },
    submitUpload() {
       this.$refs["uploadForm"].validate(valid => {
        if (valid) {
            // 使用form表单的数据格式
          let paramsData = new FormData()
          // 将上传文件数组依次添加到参数paramsData中
          this.fileList.forEach((it, index) => {
            //paramsData.append(`files[${index}]`, it.file)
            // console.log(it);
            paramsData.append('file', it.file); // 因为要上传多个文件，所以需要遍历一下才行
          });
          // 将表单数据添加到参数paramsData中
          paramsData.append('isOpen', this.uploadForm.isOpen)
          paramsData.append('viewTemplate', this.uploadForm.viewTemplate)
          paramsData.append('isTemplate', this.uploadForm.isTemplate)
          //paramsData.append('sort', this.uploadForm.sort)
          paramsData.append('type', '0')
          // 表单数据和文件一起上传,调用后端接口
          fileUpload(paramsData).then(response => {
              // console.log(result);
              if (response.code == 200) {
                  this.uploadOpen = false;
                  this.fileList = [];
                  this.uploadForm.isOpen = "0";
                  this.uploadForm.isTemplate = "0";
                  this.uploadForm.viewTemplate = undefined;
                  this.uploadForm.sort = undefined;
                  this.msgSuccess("上传成功");
                  //重新加载上传数据
                  this.uploadList = [];
                  this.queryParams.pageNum = 1;
                  this.load();
              } else {
                this.msgError(response.msg);
              }
          });
        }
      })
    },
    openTheme() {
      this.themeOpen = true;
    },
    themeLoad () {
      this.themeLoading = true;
      listTheme(this.themeQueryParams).then(response => {
        this.themeList = this.themeList.concat(response.rows);
        // console.log(this.themeList)
        this.themeTotal = response.total;
        this.themeQueryParams.pageNum++;
        this.themeLoading = false;
      });
    },
    selectTheme(value) {
      this.$set(this.configData, 'themeColor', value);
      this.themeOpen = false;
    },
    handleThemeQuery() {
      this.themeTotal = -1;
      this.themeList = [];
      this.themeQueryParams.pageNum = 1;
      this.themeOpen = true;
      this.themeLoad();
    },
    uploadOpenTheme() {
      this.themeUploadOpen = true;
    },
    cancelTheme() {
      this.themeOpen = false;
    },
    submitThemeUpload() {

      //son校验
      function isJSON(str) {
        if (typeof str == 'string') {
          try {
            var obj = JSON.parse(str);
            if(typeof obj == 'object' && obj ) {
                return true;
            } else {
                return false;
            }
          } catch(e) {
              console.log('ERROR: ' + str + '!!!' + e);
              return false;
          }
        }
        alert('It is not a string!')
      }
      //console.log(this.themeForm);

      if(isJSON(this.themeForm.themeOption) == true) {
        addTheme(this.themeForm).then(response => {
          if (response.code === 200) {
            this.themeUploadOpen = false;
            this.themeForm.isOpen = "0";
            this.themeForm.themeName = undefined;
            this.themeForm.themeOption = undefined;
            this.msgSuccess("上传成功");
            //重新加载上传数据
            this.themeList = [];
            this.themeQueryParams.pageNum = 1;
            this.themeLoad();
          } else {
            this.msgError(response.msg);
          }
        });
      } else if(isJSON(this.themeForm.themeOption) == false) {
        alert("上传格式错误，请确认上传为json格式文件");
      }
      // 表单数据和文件一起上传,调用后端接口
      
    },
    cancelThemeUpload() {
      this.themeUploadOpen = false;
    },
    deleteTheme(themeId){
       this.$confirm('是否确认删除该主题?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delTheme(themeId).then(response => {
        if (response.code === 200) {

          this.msgSuccess("删除成功");
            //重新加载上传数据
            this.themeList = [];
            this.themeQueryParams.pageNum = 1;
            this.themeLoad();
        } else {
          this.msgError(response.msg);
        }
      });
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除操作'
        });          
      });
     
    },
    deleteBackground(uploadId){
      // console.log(uploadId);
      this.$confirm('是否确认删除该背景图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUpload(uploadId).then(response => {
        if (response.code === 200) {

          this.msgSuccess("删除成功");
            //重新加载上传数据
            this.uploadList = [];
            this.queryParams.pageNum = 1;
            this.load();
        } else {
          this.msgError(response.msg);
        }
      });
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除操作'
        });          
      });
    }


  }

}
</script>

<style lang='scss' scoped>

.background-images-ul {
    margin-bottom: 20px;
}
.background-images-ul li {
    margin: 2px;
    display: inline-block;
    width: 200px;
    line-height: 25px;
    padding: 20px;
    border: 1px solid #e2e2e2;
    font-size: 14px;
    text-align: center;
    color: #666;
    transition: all .3s;
    -webkit-transition: all .3s;
    cursor: pointer;
    position: relative;
    &:hover {
      
      & > .drawing-item-delete{
        display: initial;
      }
    }
    & > .drawing-item-copy, & > .drawing-item-delete{
      display: none;
      position: absolute;
      top: 0px;
      right: 15px;
      width: 22px;
      height: 22px;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      font-size: 12px;
      border: 1px solid;
      cursor: pointer;
      z-index: 1;
   }
    & > .drawing-item-delete{
      right: 0px;
      border-color: #F56C6C;
      color: #F56C6C;
      background: #fff;
      &:hover{
        background: #F56C6C;
        color: #fff;
      }
  }
}
.border_img {
    width: 160px;
    height: 90px;
}
.background-images-ul label {
    display: inline-block;
    width: 160px;
    color: #DBEEFF;
    overflow: hidden;
}
.row {
    margin-right: -15px;
    margin-left: -15px;
}
.col-xs-6 {
    width: 50%;
    float: left;
    cursor: pointer;
    padding: 10px;
    position: relative;
    /**background-color: #b3d4ff;**/
    &:hover {
      
      & > .drawing-item-delete{
        display: initial;
      }
    }
    & > .drawing-item-copy, & > .drawing-item-delete{
      display: none;
      position: absolute;
      top: 9px;
      right: 15px;
      width: 22px;
      height: 22px;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      font-size: 12px;
      border: 1px solid;
      cursor: pointer;
      z-index: 1;
   }
    & > .drawing-item-delete{
      right: 24px;
      border-color: #F56C6C;
      color: #F56C6C;
      background: #fff;
      &:hover{
        background: #F56C6C;
        color: #fff;
      }
  }
}
.theme-plan-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    width: auto;
    height: 100px;
    overflow: hidden;
    border: 1px solid #eee;
    padding: 5px;
    border-radius: 4px;
    margin-bottom: 8px;
}
.theme-plan-color {
    width: 20px;
    height: 20px;
    margin-bottom: 10px;
    margin-left: 2px;
    margin-right: 2px;
    display: inline-block;
    border-radius: 3px;
}
.adaption_radio{
  display: flex;
  flex-direction: column;
}
.adaption_radio .el-radio{
  line-height: 25px;
}

.background-images-ul label{
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>